import util from './util.js';
import {
  login
} from './../api/user.js';
/**
 * 获取微信用户信息
 */
const wxgetUserInfo = function() {  
  return new Promise((resolve, reject) => {
    wx.getUserInfo({
      lang: 'zh_CN',
      success(res) {
        resolve(res);
      },
      fail(res) {
        reject(res);
      }
    })
  });
}
/**
 * 调用接口获取登录凭证（code）
 */
const getCodeLogin = function(successFn) {
  wx.login({
    success(res) {
      successFn(res);
    }
  })
}
/**
 * 检测微信是否登陆
 */
const chekWxLogin = function() {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          return reject({
            authSetting: false
          });
        } else {
          if (util.checkLogin()) {
            return resolve({
              userinfo: getApp().globalData.userInfo,
              isLogin: true
            });
          } else {
            wxgetUserInfo().then(userInfo => {
              return resolve({
                userInfo: userInfo,
                isLogin: false
              });
            }).catch(res => {
              return reject(res);
            })
          }
        }
      },
      fail(res) {
        return reject(res);
      }
    })
  })
}
/**
 * 
 * 授权过后自动登录
 */

const autoLogin = function() {
  return new Promise((resolve, reject) => {
    getCodeLogin((code) => {
      wxgetUserInfo().then((userInfo) => {
        userInfo.code = code;
        login(userInfo).then(res => {
          getApp().globalData.token = res.data.token;
          getApp().globalData.userInfo = res.data.userInfo;
          getApp().globalData.isLog = true;
          getApp().globalData.expiresTime = res.data.expiresTime;          
          resolve();
        })
      }).catch(err => {
        reject("系统错误，请联系管理员！");
      });
    }).catch(err => {
      reject("系统错误，请联系管理员！");
    });
  });
}

module.exports = {
  wxgetUserInfo: wxgetUserInfo,
  getCodeLogin: getCodeLogin,
  chekWxLogin: chekWxLogin,
  autoLogin: autoLogin
}